package com.qst.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qst.order.domain.UserAddress;
import com.qst.order.service.UserAddressService;
import com.qst.order.utils.JwtUtil;
import com.qst.order.utils.Result;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/address")
@RequiredArgsConstructor
@Slf4j
public class UserAddressController {


    private final UserAddressService userAddressService;

    private final JwtUtil jwtUtil;


    // 1. 查询当前所有地址
    @GetMapping
    public Result<List<UserAddress>> list(@RequestHeader("Authorization") String token) {
        String userId = jwtUtil.getClaim(token, "userId");

        List<UserAddress> list = userAddressService.getAddressByUserId(Integer.valueOf(userId));

        return Result.success(list);

    }

    // 2. 根据ID查询
    @GetMapping("/{id}")
    public UserAddress getById(@PathVariable Integer id) {
        return userAddressService.getById(id);
    }


    /**
     * 新增地址
     * 前端请求：POST /api/address
     */
    @PostMapping
    @Transactional
    public Result<UserAddress> addAddress(@Valid @RequestBody UserAddress address, @RequestHeader("Authorization") String token) {
        // 注意：userId应从登录状态中获取（如Token），这里简化处理
        log.info("添加地址：{}", address);
        Integer userId = Integer.valueOf(jwtUtil.getClaim(token, "userId"));
        address.setUserId(userId);
        UserAddress addressSaved = userAddressService.saveAddress(address);
        return Result.success(addressSaved);
    }

    /**
     * 更新地址
     * 前端请求：PUT /api/address/{id}
     */
    @PostMapping("/{id}")
    @Transactional
    public Result<UserAddress> updateAddress(
            @PathVariable Integer id,
            @RequestHeader("Authorization") String token,
            @Valid @RequestBody UserAddress address) {
        Integer userId = Integer.valueOf(jwtUtil.getClaim(token, "userId")); // 同上，从登录状态获取
        address.setId(id);
        address.setUserId(userId); // 防止越权，强制设置当前用户ID
        UserAddress updatedAddress = userAddressService.updateAddress(address);
        return Result.success(updatedAddress);
    }
    // 5. 删除地址
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {

        userAddressService.removeById(id);

        return Result.success();
    }

    // 6. 分页查询某个用户的所有地址
    @GetMapping("/user/{userId}")
    public Page<UserAddress> listByUser(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return userAddressService.page(new Page<>(page, size), wrapper);
    }

    // 7. 设置默认地址
    @PutMapping("/{id}/default")
    public boolean setDefault(@PathVariable Integer id) {
        // 先取消所有默认地址
        UserAddress update = new UserAddress();
        update.setIsDefault(false);
        userAddressService.update(update, new QueryWrapper<>());

        // 再设置当前地址为默认
        UserAddress address = new UserAddress();
        address.setId(id);
        address.setIsDefault(true);
        return userAddressService.updateById(address);
    }
}